<template>
  <div>
    <el-form :model="formInline" :rules="rules" ref="ruleFormRef" class="demo-form-inline">
      <el-form-item prop="username">
        <el-input v-model="formInline.username" placeholder="请输入账号" :keyup.enter="trimLR('username')" clearable/>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="formInline.password" placeholder="请输入密码" :keyup.enter="trimLR('password')" clearable show-password/>
      </el-form-item>
      <el-form-item prop="code" style="margin-bottom:10px" class="verifyCodeItemCss">
        <el-input
          style="margin-right: 10px;"
          v-model="formInline.code"
          placeholder="请输入验证码"
          @keyup.enter="onSubmit('ruleFormRef')"
        />
          <div id="v_container"></div>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="data.remember">自动登录</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width:100%;" @click.stop.prevent="onSubmit('ruleFormRef')">登 录</el-button>
      </el-form-item>
    </el-form>
    <!-- 项目选择弹出层 -->
    <el-dialog v-model="projectDialogVisible" append-to-body width="511px" height="604px">
      <Project :projects='projects'></Project>
    </el-dialog>
  </div>
</template>

<script setup lang='ts'>
import { reactive, ref, onMounted, nextTick } from 'vue'
import { useStore } from 'vuex';
import { useMutations } from '@/store/hooks';
import {GVerify} from '@/utils/identify'
import { getCookie } from '@/utils/cookie';
import { useRouter } from 'vue-router'
import qs from 'qs';
import useCurrentInstance from '@/utils/useCurrentInstance';
import Project from "components/common/project.vue";
import { getUrlKey } from '@/utils/utils'

const { proxy } = useCurrentInstance()
const mutationFn = useMutations(['SET_PROJECTINFO','SET_PROJECTS','SET_TENANTID','SET_ALLDEVIRE'], 'user') as {SET_PROJECTS:(any)=>{},SET_PROJECTINFO:(object)=>{},SET_ALLDEVIRE:(any)=>{}}
const store = useStore()
const router = useRouter()
const formInline = reactive({
  username: '',
  password: '',
  code:''
})
let data = reactive({
  remember:false,
})
const rules = reactive({
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
})
let verifyCode:any = {}
let win:any = window
onMounted(()=>{
  nextTick()
  if(getUrlKey('unity')){
    // unity监听/点击事件触发
    win['getButtonClick']
  }
  verifyCode = new GVerify('v_container')
  if (getCookie('remember')) {
    data.remember = true;
    const info = qs.parse(getCookie('info'));
    formInline.username = info.username;
    formInline.password = info.password;
  }
})

const btnLoading = ref(false)
const projects = ref()
const projectDialogVisible = ref(false)
const ruleFormRef = ref()
const onSubmit = async (formEl) => {
  if (!formEl) return
  await ruleFormRef.value.validate((valid: Boolean, fields: object) => {
    if (valid) {
        if (!verifyCode.validate(formInline.code)) {
          proxy.$message.error('验证码错误');
          verifyCode.refresh();
          formInline.code = '';
          return;
        }
          btnLoading.value = true
          store.dispatch('user/login', formInline).then((res) => {
              if(res?.access_token){
                getProjects()
              }
              delete res.user_info.authorities
              win.getButtonClick(JSON.stringify(res))
          }).catch(()=>{btnLoading.value = false})
      }
  })
}
const getProjects = (): void => {
  proxy.$api.getProjects().then((res) => {
    if(!res.data){
        proxy.$message({
            message: '用户凭证已过期',
            type: 'error'
        })
        return false
    }else{
      mutationFn.SET_PROJECTS(res.data)
      btnLoading.value = false
      let projectArr:Array<any> = [],company:Array<any> = []
      res.data.map((item:any) => {
          if(item.deptType == 3){
              projectArr.push(item)
          }
          if(item.parentId == 0){
              company.push(item)
          }
      })
      if(projectArr.length == 1){
          mutationFn.SET_PROJECTINFO({
              name:projectArr[0].name,
              deptId:projectArr[0].deptId,
              address:projectArr[0].extraValue,
              companyName:company[0].name,
              logo:company[0].extraValue,
          })
          //获取该项目菜单权限
          store.dispatch('user/getMenuList').then(() => {
              btnLoading.value = false
              if(!getUrlKey('unity')){
                router.push({name:'home'})
              }
          }).catch(()=>{btnLoading.value = false})
      }else{
        if(!getUrlKey('unity')){
          btnLoading.value = false
          projects.value = res.data
          projectDialogVisible.value = true
        }
      }
   }
  })
}
const trimLR = (val) => {
  if(formInline[val]) formInline[val] = formInline[val].replace(/\s+/g,'',)
}
</script>

<style lang='scss' scoped>
.verifyCodeItemCss{
  :deep(.el-form-item__content){
    display: flex;
    align-items: center;
  }
  #v_container{
    width: 35%;
    height: 40px;
  }
}
</style>
